package controller;

import helper.UserSession;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import databeans.*;

import model.CustomerDAO;
import model.FundDAO;
import model.FundHistoryDAO;
import model.FundHistoryDAOSQL;
import model.Model;
import model.PositionDAO;
import model.TransactionDAO;
import model.TransactionDAOSQL;


public class CustomerDashboardAction extends Action {
    @SuppressWarnings("unused")
	private CustomerDAO customerDAO;
    @SuppressWarnings("unused")
	private FundHistoryDAO fundHistoryDAO;
	private FundDAO fundDAO;
	private FundHistoryDAOSQL fundHistorySQLDAO;
	private PositionDAO positionDAO;
	private TransactionDAOSQL transactionDAOSQL;
	private TransactionDAO transactionDAO; 

    public CustomerDashboardAction(Model model) {
        customerDAO = model.getCustomerDAO();
        fundHistoryDAO = model.getFundHistoryDAO();
		fundDAO = model.getFundDAO();
		fundHistorySQLDAO = model.getFundHistoryDAOSQL();
		positionDAO = model.getPositoinDAO();
        transactionDAOSQL = model.getTransactionDAOSQL(); 
        transactionDAO = model.getTransactionDAO(); 
    }

    public String getName() {
        return "customerDashboard.do";
    }

    public String perform(HttpServletRequest request) {
        //ATTENTION
        // define target page

        String loginPage = "customer/customer-login.jsp";
        String successPage = "customer/customer-dashboard.jsp"; 
        
        System.out.println("Start perform");
        
        //set the employee
        Employee employee = null;
        Customer customer = null;

        
        //errors and messages will be stored here
        List<String> errors = new ArrayList<String>();
        List<String> messages = new ArrayList<String>();
        request.setAttribute("errors", errors);
        request.setAttribute("messages", messages);
        
        //check if employee has been logged in
        //request.getSession() will return the current session and if one does not exist, a new session will be cretaed.
        //request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.
        //So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.
        employee = (Employee) request.getSession(true).getAttribute("employee");
        if (employee != null) {
        	request = UserSession.removeEmployeeFromSession(request);
            errors.add("This section is closed for employee");
            return loginPage;

        } 
        
        //check if customer has actually logged in
        customer = (Customer) request.getSession(true).getAttribute("customer");
        
        if (customer != null) {
            
        	try {
        		Position [] positionList = positionDAO.getPositions(customer.getCustomerID());
                HttpSession session = request.getSession(true); 
                
                if (positionList == null) {
                    messages.add("You currently do not own any funds to show a graph for!");
                    return successPage;
                }else
                {
                	List<String> fundNames = new ArrayList<String>();
                	List<FundHistory[]> fundHistories = new ArrayList<FundHistory[]>();
                	
                	System.out.println("Num of positions found = " + positionList.length);
                	
                	for(int i =0;i< positionList.length;i++)
                	{
                		int fundID = positionList[i].getFundID();
                		
                		Calendar cal = Calendar.getInstance();
        				cal.add(Calendar.DAY_OF_MONTH, - 6);
					    FundHistory[] fundHistory = fundHistorySQLDAO.lookupFromtoNow(fundID, cal);
					    
					    System.out.println("got fund history list = " + fundHistory.length);
						
					    Fund f = fundDAO.lookup(fundID);
						String fundName = f.getName();
						System.out.println("fundName = " + fundName);
						fundNames.add(fundName);
						
						fundHistories.add(fundHistory);
                	}
                	System.out.println("================== >> fundhistories total = " + fundHistories.size());
                	request.setAttribute("fundHistories", fundHistories);
                	System.out.println("================== >> fundNames total = " + fundNames.size());
					request.setAttribute("fundNames", fundNames);
                }
                
                System.out.println("CustomerDashBoardAction+perform() in..."); 
                
                //5 latest BUY transactions
                ArrayList<databeans.Transaction> transactions_buy = transactionDAOSQL.getLastBuyTransactions(customer.getCustomerID()); 
                request.setAttribute("transactions_buy",transactions_buy); 
                System.out.println("CustomerDashBoardAction+perform()+transactions is null: "+transactions_buy==null); 
                
                ArrayList<String> fundNames_trans_buy = new ArrayList<String>();
                if(transactions_buy!=null){
                	for (int i =0; i<transactions_buy.size();i++){
                		int fundID = transactions_buy.get(i).getFundID();
                		Fund fund = fundDAO.lookup(fundID); 
                		fundNames_trans_buy.add(fund.getName());
                	}
                }
                request.setAttribute("fundNames_trans_buy",fundNames_trans_buy); 
                System.out.println("CustomerDashBoardAction+perform()+fundNames is null: "+fundNames_trans_buy==null); 
                
                
                //5 latest SELL transactions
                ArrayList<databeans.Transaction> transactions_sell = transactionDAOSQL.getLastSellTransactions(customer.getCustomerID()); 
                request.setAttribute("transactions_sell",transactions_sell); 
                System.out.println("CustomerDashBoardAction+perform()+transactions is null: "+transactions_sell==null); 
                
                ArrayList<String> fundNames_trans_sell = new ArrayList<String>();
                if(transactions_sell!=null){
                	for (int i =0; i<transactions_sell.size();i++){
                		int fundID = transactions_sell.get(i).getFundID();
                		Fund fund = fundDAO.lookup(fundID); 
                		fundNames_trans_sell.add(fund.getName());
                	}
                }
                request.setAttribute("fundNames_trans_sell",fundNames_trans_sell); 
                System.out.println("CustomerDashBoardAction+perform()+fundNames is null: "+fundNames_trans_sell==null);
                
                
                databeans.Transaction[] transactionList = transactionDAO.getTransactions(customer.getCustomerID());
                int noOfPendings = 0;
                if(transactionList.length!=0){
                	for(int i=0; i<transactionList.length; i++){
                		Date executeDate = transactionList[i].getExecuteDate();
                		if(executeDate ==null) 
                			noOfPendings++;
                	}
                }
                request.setAttribute("noOfPendings", noOfPendings); 
                
                session.setAttribute("customer", customer);
	            request.setAttribute("page", "cust-home");
	            return successPage;
	            
			} catch (Exception e) {
				System.out.println(e.getMessage());
				System.out.println(e.getCause());
				errors.add("Unable to retrieve fund History " + e.getMessage());
				return successPage;
			}
        }
		return successPage;
    }
}